#!/bin/bash

if [ -z $1 ]; then
	echo "Usage: $0 path/to/object/dir"
	exit 1
fi

DIR="$1"

cd $DIR

NUM_FILES=`csplit -f 'id' './sed.qdp' '/\! .* (/' '{*}' | wc -l`
let NUM_FILES=$NUM_FILES-2;

rm id00

for f in `ls id*`; do
	cat $f | head -n-3 > "$f.dat"
	rm $f
done

SCRIPT='sed.gp'

rm -f $SCRIPT
touch $SCRIPT
echo "set term png tiny" >> $SCRIPT
echo "set out './sed.png'" >> $SCRIPT
echo 'set datafile commentschars "#!"' >> $SCRIPT
echo "set logscale x" >> $SCRIPT
echo "set logscale y" >> $SCRIPT
echo "set xlabel 'Frequency [Hz]'" >> $SCRIPT
echo "set ylabel 'Flux density [erg cm^-2 s^-1]'" >> $SCRIPT
echo "set key under" >> $SCRIPT

echo -n "plot " >> $SCRIPT
for i in `seq -w 01 $NUM_FILES`; do
	TITLE=`grep '\! .* (' id$i.dat | cut -d' ' -f 2- | sed 's/(.*)//g'`
	echo "'id$i.dat' using 1:3:4 title '$TITLE' w errorbars, \\" >> $SCRIPT
done
let NUM_FILES=$NUM_FILES+1
TITLE=`grep '\! .* (' id$NUM_FILES.dat | cut -d' ' -f 2- | sed 's/(.*)//g'`
echo "'id$NUM_FILES.dat' using 1:3:4 title '$TITLE' w errorbars" >> $SCRIPT

gnuplot < $SCRIPT && echo "$DIR done"

rm id*
rm $SCRIPT
